import "./index.less";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { CheckList, Dropdown, Form, Toast } from "antd-mobile";
import MySearchBar from "@/components/MySearchBar";
import Listmeta from "../Guide/components/listmeta";
import { PageHeaderNew } from "@/components";
import { getGuide, getSearch } from "../../service";
import { Spin } from "antd";

export default function Branch() {
  const navigate = useNavigate();
  const searchRef = useRef(null);
  const selectRef = useRef(null);
  const [form] = Form.useForm();
  const [searchValue, setSearchValue] = useState<undefined | string>();
  const [panelData, setPanelData] = useState([]);
  const [listData, setListData] = useState([]);
  const [currentSel, setCurrentSel] = useState("");
  const [latLng, setLatLng] = useState([]);
  const [dropTitle, setDropTitle] = useState("全部类型");
  const [loaing, setLoaing] = useState(true);

  const getGuideList = async () => {
    try {
      const res = await getGuide();
      if (res?.success && res?.code === 200) {
        res?.data?.unshift({ appTypeName: "全部类型", id: "" });
        setPanelData(res?.data);
      }
    } catch (error) {
      console.log(error);
    }
  };
  const getListData = async (value?: any) => {
    try {
      const res = await getSearch({
        Typename: value !== "" ? searchValue : "",
        pid: currentSel,
        lat: latLng[0],
        lng: latLng[1],
      });
      if (res && res?.success) {
        setListData(res?.data);
        setLoaing(false);
      } else {
        Toast.show(res?.msg);
        setLoaing(false);
      }
    } catch (error) {
      console.log(error);
    }
  };
  const formPosition = () => {
    let datas = JSON.parse(localStorage.getItem("address")) || {};
    let latlng = [datas?.latitude, datas?.longitude];
    setLatLng(latlng);
  };

  useEffect(() => {
    getGuideList();
    formPosition();
  }, []);
  useEffect(() => {
    if (latLng?.length > 0) getListData();
  }, [currentSel, latLng]);

  return (
    <div className="Branch_contarnier">
      <div className="header-bg"></div>
      <PageHeaderNew title="网点查询" goBack={() => navigate(-1)} />

      <div className="Branch_content">
        {/* 搜索框 */}
        <div className="Branch_content_search">
          <MySearchBar
            searchValue={searchValue}
            setSearchValue={setSearchValue}
            searchRef={searchRef}
            onSearch={(v: any) => getListData(v)}
          />
        </div>

        {/* 下拉选择 */}
        <div className="Branch_content_select">
          <Dropdown ref={selectRef}>
            <Dropdown.Item key="allType" title={dropTitle}>
              <div style={{ padding: 12 }}>
                <CheckList
                  className="branch_panel_list"
                  value={[currentSel]}
                  onChange={(v: any) => {
                    if (v?.length > 0) {
                      setCurrentSel(v[0]);
                      setDropTitle(
                        panelData?.filter((i) => i.id === v[0])[0]?.appTypeName
                      );
                      selectRef?.current?.close();
                    } else selectRef?.current?.close();
                  }}
                >
                  {panelData?.length > 0 &&
                    panelData?.map((item: any, index: number) => {
                      return (
                        <CheckList.Item
                          className="branch_panel_list_item"
                          value={item?.id}
                          key={item?.id}
                        >
                          {item?.appTypeName}
                        </CheckList.Item>
                      );
                    })}
                </CheckList>
              </div>
            </Dropdown.Item>
          </Dropdown>
        </div>

        {/* 列表 */}
        <div className="Branch_content_list">
          {listData?.length > 0 &&
            listData?.map((item: any, index: number) => {
              return (
                <Listmeta
                  data={item}
                  key={`bcl_list_${index}`}
                  onClick={() =>
                    navigate(`/lifeCircle/guide/searchpage/guidelocation`, {
                      state: { data: item, type: "branch", latlng: latLng },
                    })
                  }
                />
              );
            })}

          <div
            style={{
              width: "100%",
              height: 120,
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Spin
              tip="加载中..."
              size="large"
              spinning={loaing}
              style={{ zoom: 2 }}
            ></Spin>
          </div>
        </div>

        <Form form={form} style={{ display: "none" }}>
          <Form.Item name="address" label="服务地址"></Form.Item>
        </Form>
      </div>
    </div>
  );
}
